<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:doc="livcos.org/ns/doc"
  xmlns:m="livcos.org/ns/map"
  xmlns:u="livcos.org/ns/cosmos/update"
  exclude-result-prefixes="m u doc">
  
<xsl:import href="../../web/editor/integrity.xsl"/>

	<xsl:template match="m:map/m:body/*[@id]">
		<xsl:variable name="itemId">
			<xsl:value-of select="following-sibling::m:item[1]/@id"/>
			<xsl:if test="not(following-sibling::m:item[1]/@id)">
				<xsl:value-of select="preceding-sibling::m:item[1]/@id"/>
			</xsl:if>
		</xsl:variable>
		<u:insert select=".//*[@id = '{$itemId}']">
			<u:move-from select="../*[@id = '{@id}']"/>
		</u:insert>
	</xsl:template>
	
	<xsl:template match="m:map/m:body/m:item" priority="2">
		<xsl:apply-templates select="*"/>
	</xsl:template>
	
	<xsl:template match="m:item/m:rels/*[@id]">
		<u:insert select=".//*[@id = '{../../@id}']">
			<u:move-from select="*/*[@id = '{@id}']"/>
		</u:insert>
	</xsl:template>
	
	<xsl:template match="m:item/m:rels/m:rel" priority="2">
		<xsl:apply-templates select="*"/>
	</xsl:template>
	
	<xsl:template match="m:body/doc:citation" priority="2">
		<xsl:variable name="item"
			select="if (following-sibling::m:item) then following-sibling::m:item[1] else preceding-sibling::m:item[1]"/>
		<!-- replace the citation with a new item -->
		<u:insert select="m:body">
			<u:namespace prefix="m" uri="livcos.org/ns/map"/>
			<item id="{{new-id()}}" xmlns="livcos.org/ns/map">
				<label>
					<xsl:value-of select="doc:title"/>
					<xsl:if test="not(doc:title)"><xsl:value-of select="@ref"/></xsl:if>
				</label>
				<rels id="{{new-id()}}" group="sys">
					<rel id="{{new-id()}}" ref="#{$item/@id}"/>
				</rels>
				<doc:link id="{{new-id()}}" ref="{@ref}"/>
				<xsl:if test="doc:content">
					<doc:paragraph id="{{new-id()}}"><xsl:copy-of select="doc:content/node()"/></doc:paragraph>
				</xsl:if>
			</item>
		</u:insert>
		<u:delete select=".//*[@id = '{@id}']"/>
		<!-- relation to the new item -->
		<u:context select="m:body/m:item[@id = '{$item/@id}']">
			<u:namespace prefix="m" uri="livcos.org/ns/map"/>
			<xsl:if test="not($item/m:rels[@group = 'main'])">
				<u:insert select=".">
					<rels id="{{new-id()}}" group="main" xmlns="livcos.org/ns/map"/>
				</u:insert>
			</xsl:if>
			<u:insert select="m:rels[@group = 'main']">
				<u:namespace prefix="m" uri="livcos.org/ns/map"/>
				<rel id="{{new-id()}}" xmlns="livcos.org/ns/map">
					<u:attribute name="ref">
						<xsl:text>#</xsl:text>
						<u:copy-of select="../../*[last()]/@id"/>
					</u:attribute>
				</rel>
			</u:insert>
		</u:context>
	</xsl:template>
	
</xsl:stylesheet>
